import { RouteRecordRaw } from "vue-router";
import { getMenusApi } from "../../api/menu";
import { SET_MENUS } from "../mutation-types";
import router from '../../router'
import Layout from '@/Layout/index.vue'

export default {
    namespaced : false,
    state : {
        routes : [],
        menus : []
    },
    mutations : {
        [SET_MENUS] (state, menus:any[]) {
            state.menus = menus
        }
    },
    actions : {
        async getMenus({ commit }, data) {
            let menus:any[] = []

            let routes:RouteRecordRaw[] = []

            const buildMenus = (target:RouteRecordRaw[], menusTarget:any[], path:string, parentId=0) => {
                for(let i = 0; i < data.length; i ++) {
                    const item = data[i]
                    if(parentId == item.parentId) {
                        let route:RouteRecordRaw = {
                            path : path + item.path,
                            name : item.path + item.id,
                            component : parentId == 0 ? Layout : () => import('/src/view/' + item.component),
                            meta : {title : item.name, keep_alive : item.keepAlive == 1},
                            children : []
                        }

                        let menu:any = {
                            ...item,
                            routePath : route.path,
                            routeName : route.name,
                            children : []
                        }

                        target.push(route)

                        menusTarget.push(menu)

                        

                        buildMenus(route.children!, menu.children, route.path + '/', item.id)
                        if(route.children?.length == 0) {
                            delete route.children
                            delete menu.children
                        }
                    }
                }
            }

            buildMenus(routes, menus, '/')

            commit(SET_MENUS, menus)
            routes.forEach(route => {
                router.addRoute(route)
            })
        }
    }
}